<template>
	<!-- 基础表单校验 -->
	<view style="padding: 0 10rpx;">
		<uni-forms ref="baseForm" labelAlign="right" :rules="rules" :modelValue="baseFormData.workList">
			<uni-section title="基础信息" type="line"></uni-section>
			<uni-forms-item label="日期:" required name="workDate">
				<uni-datetime-picker 
				type="date" 
				:clearIcon="false" 
				v-model="baseFormData.workList.workDate"/>
			</uni-forms-item>
			<uni-forms-item  label="团队:" name="teamId">
				<uni-data-picker 
				placeholder="请选择团队" 
				:localdata="team" 
				@change="getProjectsByCondition"
				v-model="baseFormData.workList.teamId" />
			</uni-forms-item>
			<uni-forms-item  label="项目:" required name="projectId">
				<uni-data-picker 
				placeholder="请选择工程" 
				:localdata="project" 
				@change="getEmployee"
				v-model="baseFormData.workList.projectId" />
			</uni-forms-item>
			<uni-forms-item label="名称:" required name="name">
				<uni-easyinput v-model="baseFormData.workList.name" placeholder="请输入名称" />
			</uni-forms-item>
			<uni-forms-item label="人员:" required name="worker">
				<uni-data-checkbox 
				mode="button" 
				multiple 
				v-model="baseFormData.employees" 
				:localdata="worker">
				</uni-data-checkbox>
			</uni-forms-item>
			<uni-section title="详细信息" type="line"></uni-section>
			<uni-forms-item label="工作状态:" name="workStatus">
				<uni-data-checkbox v-model="baseFormData.workList.workStatus" 
				:localdata="workStatus" 
				/>
			</uni-forms-item>
			<uni-forms-item label="加班时间:" v-if="baseFormData.workList.workStatus == 'EXTWORK'">
				<uni-datetime-picker 
				v-model="baseFormData.ext_work_time == null ? '' : baseFormData.ext_work_time" 
				type="datetimerange" 
				start="2021-7-1 00:00:00" 
				@change="extWorkChange"
				rangeSeparator="至" />
			</uni-forms-item>
			<uni-forms-item label="出差情况:" v-if="baseFormData.workList.workStatus == 'ERRAND'">
				<uni-easyinput v-model="baseFormData.workList.errandPlace" placeholder="出差地点" />
			</uni-forms-item>
			<uni-forms-item label="备注:" name="note">
				<uni-easyinput type="textarea" v-model="baseFormData.workList.note" placeholder="请输入备注" />
			</uni-forms-item>
			<uni-forms-item label="现场图片:" name="images">
				<robby-image-upload v-model="baseFormData.imageList"
				@delete="deleteImage" 
				@add="addImage"
				limit="9"
				></robby-image-upload>
				<!-- <button type="primary" @click="upLoad" size="mini" style="background-color: #007aff;">上传</button> -->
			</uni-forms-item>
			<uni-section title="费用支出" type="line"></uni-section>
			<uni-table ref="table" :loading="loading" stripe emptyText="暂无消费记录">
				<uni-tr>
					<uni-th width="160" align="center">类别</uni-th>
					<uni-th align="center"width="100">费用</uni-th>
					<uni-th  align="center">设置</uni-th>
				</uni-tr>
				<uni-tr  v-for="(item,index) in baseFormData.costLists" :key="index" >
					<uni-td align="center" class="cost-list">
						<uni-data-picker
						popup-title="支出类别"
						placeholder="请选择类别" 
						:localdata="cost_category"
						v-model="item.value"
						>
						</uni-data-picker>
					</uni-td>
					<uni-td align="center" class="cost-list"><uni-easyinput v-model="item.cost" placeholder="0.00"/></uni-td>
					<uni-td class="cost-list">
						<view class="uni-group" style="text-align: center;">
							<button class="uni-button" size="mini" type="warn" @click="delCost(index)" style="vertical-align: middle;">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
			<view style="width: 100%; text-align: center;margin: 15px auto;">
				<button type="default" size="mini" style="background-color: #007AFF;color: #fff;" @click="addCost">点击添加一条消费记录</button>
			</view>
		</uni-forms>
		<button type="primary" style="margin: 0 10upx 50upx 10upx;background-color: #007aff;" @click="submit">提交</button>
	</view>
</template>

<script>
	import robbyImageUpload from '@/components/robby-image-upload/robby-image-upload.vue'
	export default {
	    components: {robbyImageUpload},
		data() {
			return {
				// deepLength: 2,
				// defaultChooseList:[0,0],
				workListData: [],
				isEdit: false,
				isClickUpload: false,
				isFromIndex: false,
				datetimesingle: 1627529992399,
				datetimerange: [],
				team: [],
				project: [],
				worker: [],
				workStatus: [{
					text: '正常',
					value: 'NORMAL'
				},{
					text: '加班',
					value: 'EXTWORK'
				},{
					text: '出差',
					value: 'ERRAND'
				}],
				item: [],
				imageList: [],
				fileList: [],
				images: [],
				delId: [],
				fileIds: [],
				imgStyle: {
					"height": 100,   // 边框高度
					"width": 100,    // 边框宽度
					"border":{ // 如果为 Boolean 值，可以控制边框显示与否
						"color":"#eee",     // 边框颜色
						"width":"1px",      // 边框宽度
						"style":"solid",    // 边框样式
						// "radius":"50%"      // 边框圆角，支持百分比
					}
				},
				costList: [],
				baseFormData: {
					workList: {
						id: '',
						workDate: '',
						teamId : '',
						projectId: '',
						name: '',
						note: '',
						workStatus: 'NORMAL',
						extWorkStart: '',
						extWorkEnd: '',
						errandPlace: '',
						employee: '',
						image: ''
					},
					ext_work_time: [],
					costLists: [],
					employees: [],
					imageList: []
				},
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '名称不能为空'
						}]
					},
					projectId: {
						rules: [{
							required: true,
							errorMessage: '请先选择工程'
						}]
					},
					workDate: {
						rules: [{
							required: true,
							errorMessage: '请选择日期'
						}]
					},
					worker: {
						rules: [{
							format: 'array'
						},
						{
							validateFunction: function(rule, value, data, callback) {
								if (value.length < 1) {
									callback('请选择工作人员')
								}
								return true
							}
						}]
					}
				},
				cost_category: [],
			}
		},
		onLoad(ev) {
			this.getTeam();
			this.getCostCategory();
			this.getProjectsByCondition();
			this.getEmployee();
			this.initBaseFormData(ev.id);
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.baseForm.setRules(this.rules)
		},
		onShareAppMessage(res) {
		    if (res.from === 'button') {// 来自页面内分享按钮
		      console.log(res.target)
		    }
		    return {
		      title: '大家都在用这款小工具管理项目，快来试试吧！！！',
		      path: '/pages/index/index'
		    }
		},
		computed: {
			// newProject() {
			// 	return this.baseFormData.workList.projectId;
			// }
		},
		watch: {
			// newProject(val) {
			// 	this.getWorkersByProject(val);
			// },
			// immediate: true
		},
		methods: {
			initBaseFormData(id) {
				if(id != null) {
					this.isEdit = true;
					var token = this.$dry.getToken();
					var data = this.$request.run("getWorkListById",token);
					uni.request({
						url: data.url,
						method: data.method,
						header: data.header,
						data: {
							"workListId": id
						},
						success: data => {
							var formData = data.data;
							this.baseFormData.workList = formData.workList;
							var costLists = formData.costLists;
							if(costLists.length > 0) {
								costLists.forEach(c => {
									c.value = c.pathList[0] + '-' + c.pathList[1];
								})
								this.baseFormData.costLists = costLists;
							}
							var employee = formData.employees;
							if(employee.length > 0) {
								var newEmployee = [];
								employee.forEach(e => {
									newEmployee.push(e.id);
								})
								this.baseFormData.employees = newEmployee;
							}
							if(formData.workList.workStatus == 'EXTWORK'){
								this.baseFormData.ext_work_time[0] = formData.workList.extWorkStart;
								this.baseFormData.ext_work_time[1] = formData.workList.extWorkEnd;
							}
							if(formData.imageList.length > 0) {
								formData.imageList.forEach(i => {
									this.images.push(
									{
										id: i.id,
										url: i.url
									});
									this.baseFormData.imageList.push(i.url);
								})
							}
						}
					})
				}
			},
			getEmployee() {
				var token = this.$dry.getToken();
				if(token){
					var data = this.$request.run("listEmployeeByConditions",token);
				    uni.request({
				    	url: data.url,
				    	method: data.method,
				    	header: data.header,
				    	data: {
							"projectId": this.baseFormData.workList.projectId,
							"employeeStatus": 'NORMAL'
						},
				    	success: data => {
				    		var worker = data.data;
							var newItems = [];
							if(worker.length != 0){
								worker.forEach(e => {
									newItems.push({
										text: e.realName == null || e.realName == '' ? e.nickName : e.realName,
										value: e.id
									});
								});
							}
							this.worker= newItems;
				    	},
				    	fail: (data, code) => {
				    		console.log('fail' + JSON.stringify(data));
				    	}
				    })
				}
			},
			async getCostCategory() {
				this.cost_category = await this.$dry.getCostCategory();
			},
			async getTeam() {
				var list = await this.$dry.getTeams(true);
				var team = [{
					text: "请选择团队",
					value: ''
				}];
				list.forEach(e => {
					team.push({
						text: e.name,
						value: e.id
					})
				})
				this.team = team;
				
			},
			async getProjectsByCondition(e) {
				var projectList = this.$dry.get("project");
				var teamId = '';
				if(e) {
					teamId = e.detail.value[0].value;
				}
				var token = this.$dry.getToken();
				if (token) {
					projectList = await this.getProject(teamId);
				}
				if(projectList.length != 0) {
					var newList = [{
						text: "请选择项目",
						value: ''
					}]
					projectList.forEach(p => {
						newList.push({
							text: p.name,
							value: p.id,
						});
					});
					this.project = newList;
				}
				else{
					this.project = [];
				}
			},
			getProject(teamId) {
				var token = this.$dry.getToken();
				var data = [];
				if (token) {
					data = this.$request.run("queryProjectsByCondition",token);
					return new Promise((resolve) => {
						uni.request({
							url: data.url,
							method: data.method,
							header: data.header,
							data: {
								"teamId": teamId,
								"queryAll": false
							},
							success: data => {
								resolve(data.data);
							}
						});
					});
				}
			},
			addImage(e){
				this.imageList = this.imageList.concat(e.paths);
				this.fileList = this.fileList.concat(e.files);
			},
			deleteImage(e){
				this.images.forEach(i => {
					if(i.url == e.currentImage){
						this.delId.push(i.id);
					}
				})
				for(let i = 0; i < this.imageList.length; i++){
					if(e.currentImage == this.imageList[i]){
						this.imageList.splice(i,1);
					}
				}
				for(let j = 0; j < this.fileList.length; j++){
					if(e.currentImage == this.fileList[j].path){
						this.fileList.splice(j,1);
					}
				}
			},
			onConfirm(e) {
				// e 确认后选中的数据
				this.pickerText = JSON.stringify(e)
			},
			addCost() {
				if (this.baseFormData.costLists.length < 9) {
					this.baseFormData.costLists.push({
						value: "1-1",
						id: '',
						categoryId: 0,
						cost: 0
					});
				} else {
					uni.showToast({
						title: '最多添加9个',
						icon: 'none'
					});
				}
			},
			delCost(index) {
				//console.log(index);
				this.baseFormData.costLists.splice(index, 1)
			},
			submit() {
				this.$refs['baseForm'].validate().then(async res => {
					var fileLists = [];
					if(this.fileList.length > 0) {
						fileLists = await this.$oss.saveImages(this.fileList);
					}
					var token = this.$dry.getToken();
					if(token){
						uni.showToast({
							title: "正在提交",
							icon: "loading",
							duration: 2000
						});
						setTimeout(() => {
							if(fileLists.length > 0) {
								this.isClickUpload = true;
								fileLists.forEach(file => {
									this.fileIds.push(file.id);
								})
							}
							var data = [];
							if(this.isEdit){
								this.baseFormData.workList.image = this.isClickUpload == true ? this.$dry.getImgIds(this.images,this.fileIds,this.delId).join(",") : this.workListData.image;
							}
							else{
								this.baseFormData.workList.image = this.isClickUpload == true ? this.fileIds.join(",") : "";
							}
							this.baseFormData.workList.employee = this.baseFormData.employees.join(",");
							if(this.baseFormData.costLists.length > 0) {
								this.baseFormData.costLists.forEach(cost => {
									cost.categoryId = cost.value.split("-")[1];
								})
							}
							if(this.isEdit) {
								this.$request.addOrEdit("updateWorkList",this.baseFormData,token,true);
							} else {
								this.$request.addOrEdit("addWorkList",this.baseFormData,token,false);
							}
							uni.switchTab({
								url: '../work-list/work-list'
							})
						}, 2000);
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			format(dateStr) {
				var date = this.parse(dateStr)
				var diff = Date.now() - date.getTime();
				if (diff < this.UNITS['天']) {
					return this.humanize(diff);
				}
				var _format = function(number) {
					return (number < 10 ? ('0' + number) : number);
				};
				return date.getFullYear() + '-' + _format(date.getMonth() + 1) + '-' + _format(date.getDate()) + ' ' +
					_format(date.getHours()) + ':' + _format(date.getMinutes());
			},
			parse(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
				var a = str.split(/[^0-9]/);
				return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
			},
			extWorkChange(e){
				this.baseFormData.ext_work_time = e;
				this.baseFormData.workList.extWorkStart = this.baseFormData.ext_work_time[0];
				this.baseFormData.workList.extWorkEnd = this.baseFormData.ext_work_time[1];
			},
		}
	}
</script>

<style>
	.container {
		height: 100%;
		/* #ifndef APP-NVUE */
		display: flex;
		max-width: 500px;
		padding: 0 15px;
		/* #endif */
		flex-direction: column;
	}
	.title {
		font-size: 14px;
		font-weight: bold;
		margin: 20px 0 5px 0;
	}
	
	.data-pickerview {
		height: 400px;
		border: 1px #e5e5e5 solid;
	}
	.cost-dynamic-box {
		margin-bottom: 15px;
		width: 100%;
	}
</style>
